#!/usr/bin/env bash
# Copyright (c) 2022, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

# Script to run a benchmark compiled using dart2wasm. Assumes the Dart repo's
# directory structure.

set -e

function follow_links() {
  file="$1"
  while [ -h "$file" ]; do
    # On Mac OS, readlink -f doesn't work.
    file="$(readlink "$file")"
  done
  echo "$file"
}

# Unlike $0, $BASH_SOURCE points to the absolute path of this file.
PROG_NAME="$(follow_links "$BASH_SOURCE")"

# Handle the case where dart-sdk/bin has been symlinked to.
PROG_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
SDK_DIR="$(cd "${PROG_DIR}/../../.." ; pwd -P)"

RUN_WASM="$SDK_DIR/pkg/dart2wasm/bin/run_wasm.js"

function host_arch() {
  # Use uname to determine the host architecture.
  case `uname -m` in
    x86_64)
    echo "x64"
    ;;
    aarch64 | arm64 | armv8*)
    echo "arm64"
    ;;
    *)
    echo "Unsupported host architecture" `uname -m` >&2
    exit 1
    ;;
  esac
}

function host_os() {
  if [[ `uname` == 'Darwin' ]]; then
    echo 'macos'
  else
    echo 'linux'
  fi
}

D8_BIN="$SDK_DIR/third_party/d8/$(host_os)/$(host_arch)/d8"
JSSHELL_BIN="$SDK_DIR/third_party/firefox_jsshell/js"
JSC_BIN="$SDK_DIR/third_party/jsc/jsc"

SHELL_BIN="$D8_BIN"
SHELL_OPTIONS=()
SHELL_ARG_SEPERATOR="--"
MJS_FILE=""
WASM_FILE=""
LINEAR_WASM_FILES=()
ARGS=()
while [ $# -gt 0 ]; do
  case "$1" in
    --d8)
      SHELL_BIN="$D8_BIN"
      SHELL_ARG_SEPERATOR="--"
      shift
      ;;

    --jsshell)
      SHELL_BIN="$JSSHELL_BIN"
      SHELL_ARG_SEPERATOR=""
      shift
      ;;

    --jsc)
      SHELL_BIN="$JSC_BIN"
      SHELL_ARG_SEPERATOR="--"
      shift
      ;;

    --shell-option=*)
      SHELL_OPTIONS+=("${1#--shell-option=}")
      shift
      ;;

    *.wasm)
      if [ -z "$WASM_FILE" ]; then
        # First wasm file is the actual dart program
        WASM_FILE="$(realpath "$1")"
        MJS_FILE="${WASM_FILE%.wasm}.mjs"
      else
        # Following wasm files are imported linear memory modules
        LINEAR_WASM_FILES+=("$1")
      fi
      shift
      ;;

    *)
      # Any arguments that are not the above will be arguments to the dart's
      # main function.
      break
      ;;
  esac
done

exec "$SHELL_BIN" "${SHELL_OPTIONS[@]}" "$RUN_WASM" $SHELL_ARG_SEPERATOR "$MJS_FILE" "$WASM_FILE" "${LINEAR_WASM_FILES[@]}" -- "$@"
